package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

public class CustomerRelationAddStaffFragment extends Fragment implements OnClickListener {

  public static final String EXTRA_ORDCODE =
      "com.isunland.managesystem.ui.CustomerRelationAddStaffFragment.EXTRA_ORDCODE";
  public static final String EXTRA_CUSTOMER_CODE =
      "com.isunland.managesystem.ui.CustomerRelationAddStaffFragment.EXTRA_CUSTOMER_CODE";
  private static final int REQUEST_BIRTH_DATE = 0;
  private static final int REQUEST_BEST_VISIT = 1;
  private static final int SAVE = 2;
  private static final int SAVE_CHECK = 3;
  private BaseVolleyActivity mActivity;
  private EditText etDirectorNumber; // 编号
  private EditText etDepartmentperson;// 员工姓名
  private RadioGroup tvDirectorSex;// 性别
  private RadioButton rbBoy;
  private RadioButton rbGirl;
  private EditText etDirectordial;// 联系 电话
  private EditText etDirectorEmail;// 邮箱
  private EditText etPositionConstruction;// 职务说明
  private TextView mTvBithDateAddDepartmentPerson;// 出生日期
  private EditText mTvBirthHomeAddDepartmentPerson;// 家乡地
  private EditText mTvHomeAddressAddDepartmentPerson;// 家庭住址
  private EditText mTvGraduateSchoolAddDepartmentPerson;// 毕业院校
  private EditText mTvPersonalEnjoyAddDepartmentPerson;// 个人喜好
  private TextView mTvBestVisitTimeAddDepartmentPerson;// 最佳拜访那个时间
  private EditText mTvPersonalRequireAddDepartmentPerson;// 个人需求
  private EditText mTvFamilyRelationAddDepartmentPerson;// 家庭成员及关系
  private EditText mTvOtherRemarkAddDepartmentPerson; // 其它说明与备注

  HashMap<String, String> mProcessEdit;
  private static final String BOY = "boy";
  private static final String GRIL = "gril";
  private static String staffGender = BOY;
  private String mBlongOrgCode;
  private String mBlongCustomerCode;
  private String mBirthDate;
  private String mVisitTime;
  private String mId = "";//本次记录id

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    mActivity = (BaseVolleyActivity) getActivity();
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.addPerson);
    mBlongOrgCode = getArguments().getString(EXTRA_ORDCODE);
    mBlongCustomerCode = getArguments().getString(EXTRA_CUSTOMER_CODE);
    mId = UUID.randomUUID().toString();
    LogUtil.i("blongOrgCode++++++++++++++++++" + mBlongOrgCode);
    LogUtil.i("blongCustomerId++++++++++++++++++" + mBlongCustomerCode);
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_add_department_person, container, false);
    etDirectorNumber = (EditText) view.findViewById(R.id.et_directorNumber_departmentPerson);
    etDepartmentperson = (EditText) view.findViewById(R.id.et_departmentperson_departmentPerson);
    tvDirectorSex = (RadioGroup) view.findViewById(R.id.tv_directorSex_departmentPerson);
    rbBoy = (RadioButton) view.findViewById(R.id.rb_boy_epartmentPerson);
    rbGirl = (RadioButton) view.findViewById(R.id.rb_girl_epartmentPerson);
    etDirectordial = (EditText) view.findViewById(R.id.et_directordial_departmentPerson);
    etDirectorEmail = (EditText) view.findViewById(R.id.et_directorEmail_departmentPerson);
    etPositionConstruction =
        (EditText) view.findViewById(R.id.et_positionConstruction_departmentPerson);

    mTvBithDateAddDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_bithDate_addDepartmentPerson);
    mTvBirthHomeAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_birthHome_addDepartmentPerson);
    mTvHomeAddressAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_homeAddress_addDepartmentPerson);
    mTvGraduateSchoolAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_graduateSchool_addDepartmentPerson);
    mTvPersonalEnjoyAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_personalEnjoy_addDepartmentPerson);
    mTvBestVisitTimeAddDepartmentPerson =
        (TextView) view.findViewById(R.id.tv_bestVisitTime_addDepartmentPerson);
    mTvPersonalRequireAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_personalRequire_addDepartmentPerson);
    mTvFamilyRelationAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_familyRelation_addDepartmentPerson);
    mTvOtherRemarkAddDepartmentPerson =
        (EditText) view.findViewById(R.id.tv_otherRemark_addDepartmentPerson);

    mTvBithDateAddDepartmentPerson.setOnClickListener(this);
    mTvBestVisitTimeAddDepartmentPerson.setOnClickListener(this);
    tvDirectorSex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          case R.id.rb_boy_epartmentPerson:
            staffGender = BOY;
            break;
          case R.id.rb_girl_epartmentPerson:
            staffGender = GRIL;
            break;

          default:
            break;
        }
      }
    });
    DynamicConfigLab config =
        DynamicConfigLab.newInstance(mActivity, getString(R.string.module_deptColumns));
    config.autoConfigTitle(view);
    config.autoConfigVisiblity(view);
    return view;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //		inflater.inflate(R.menu.menu_confirm, menu);
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_save:
        isIfComplete(SAVE);
        break;
      //保存并审核通过
      case R.id.menu_item_submit:
        isIfComplete(SAVE_CHECK);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void isIfComplete(int requestCode) {
    String email = etDirectorEmail.getText().toString().trim();
    String staffName = etDepartmentperson.getText().toString().trim();
    if (TextUtils.isEmpty(staffName)) {
      Toast.makeText(getActivity(), R.string.completeStaff, Toast.LENGTH_SHORT).show();
    } else {
      if (TextUtils.isEmpty(email)) {
        if (SAVE == requestCode) {
          volleyPostSave(SAVE);
        } else if (SAVE_CHECK == requestCode) {
          showDialog(SAVE_CHECK, null);
        }
      } else {
        if (!MyUtils.isEmail(email)) {
          Toast.makeText(getActivity(), R.string.emailPatternWrong, Toast.LENGTH_SHORT).show();
          return;
        }
        if (SAVE == requestCode) {
          volleyPostSave(SAVE);
        } else if (SAVE_CHECK == requestCode) {
          showDialog(SAVE_CHECK, null);
        }
      }
    }
  }

  private void volleyPostSave(final int requestCode) {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_STAFF_SAVE);
    String staffNo = etDirectorNumber.getText().toString();
    String staffName = etDepartmentperson.getText().toString();

    String gender = "";
    if (staffGender.equalsIgnoreCase(BOY)) {
      gender = getResources().getString(R.string.boy_customerRel);
    } else if (staffGender.equalsIgnoreCase(GRIL)) {
      gender = getResources().getString(R.string.girl_customerRel);
    }

    String contactNum = etDirectordial.getText().toString();
    String contactMail = etDirectorEmail.getText().toString();
    String dutyDescript = etPositionConstruction.getText().toString();

    mProcessEdit = new HashMap<String, String>();
    mProcessEdit.put("id", mId); //本次记录id
    if (staffNo != null) {
      mProcessEdit.put("staffNo", staffNo);
    } else {
      mProcessEdit.put("staffNo", "");
    }
    if (staffName != null) {
      mProcessEdit.put("staffName", staffName);
    } else {
      mProcessEdit.put("staffName", "");
    }
    if (gender != null) {
      mProcessEdit.put("staffGender", gender);
    } else {
      mProcessEdit.put("staffGender", "");
    }
    if (mBlongOrgCode != null) {
      mProcessEdit.put("blongOrgCode", mBlongOrgCode);
    } else {
      mProcessEdit.put("blongOrgCode", "");
    }

    if (mBlongCustomerCode != null) {
      mProcessEdit.put("blongCustomerCode", mBlongCustomerCode);
    } else {
      mProcessEdit.put("blongCustomerCode", "");
    }
    if (contactNum != null) {
      mProcessEdit.put("contactNum", contactNum);
    } else {
      mProcessEdit.put("contactNum", "");
    }
    if (contactMail != null) {
      mProcessEdit.put("contactMail", contactMail);
    } else {
      mProcessEdit.put("contactMail", "");
    }

    if (dutyDescript != null) {
      mProcessEdit.put("dutyDescript", dutyDescript);
    } else {
      mProcessEdit.put("dutyDescript", "");
    }

    if (!TextUtils.isEmpty(mBirthDate)) {
      mProcessEdit.put("birthDate", mBirthDate);
    } else {
      mProcessEdit.put("birthDate", "");
    }
    if (!TextUtils.isEmpty(mTvBirthHomeAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("homeArea", mTvBirthHomeAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("homeArea", "");
    }
    if (!TextUtils.isEmpty(mTvHomeAddressAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("homeAddress",
          mTvHomeAddressAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("homeAddress", "");
    }
    if (!TextUtils.isEmpty(mTvGraduateSchoolAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("graduateCollege",
          mTvGraduateSchoolAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("graduateCollege", "");
    }
    if (!TextUtils.isEmpty(mTvPersonalEnjoyAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("personalHobby",
          mTvPersonalEnjoyAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("personalHobby", "");
    }
    if (!TextUtils.isEmpty(mVisitTime)) {
      mProcessEdit.put("visitTime",
          mTvBestVisitTimeAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("visitTime", "");
    }
    if (!TextUtils.isEmpty(mTvPersonalRequireAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("personalNeed",
          mTvPersonalRequireAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("personalNeed", "");
    }
    if (!TextUtils.isEmpty(mTvFamilyRelationAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("familyRelation",
          mTvFamilyRelationAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("familyRelation", "");
    }
    if (!TextUtils.isEmpty(mTvOtherRemarkAddDepartmentPerson.getText().toString().trim())) {
      mProcessEdit.put("explainRemark",
          mTvOtherRemarkAddDepartmentPerson.getText().toString().trim());
    } else {
      mProcessEdit.put("explainRemark", "");
    }
    LogUtil.i("params=" + mProcessEdit.toString());
    mActivity.volleyPost(url, mProcessEdit, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (SAVE == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else if (SAVE_CHECK == requestCode) {
              staffChek();
            }
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  // 员工审核
  private void staffChek() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_STAFF_CHECK);
    HashMap<String, String> mStaff = new HashMap<String, String>();
    mStaff.put("ids", "'" + mId + "'");
    mStaff.put("dataStatus", "publish");

    mActivity.volleyPost(url, mStaff, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  public static Fragment newInstance(String orgCode, String customerCode) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_ORDCODE, orgCode);
    bundle.putString(EXTRA_CUSTOMER_CODE, customerCode);
    CustomerRelationAddStaffFragment fragment = new CustomerRelationAddStaffFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.tv_bithDate_addDepartmentPerson:
        showDialog(REQUEST_BIRTH_DATE, new Date());
        break;
      case R.id.tv_bestVisitTime_addDepartmentPerson:
        showDialog(REQUEST_BEST_VISIT, new Date());
        break;

      default:
        break;
    }
  }

  private void showDialog(int requestCode, Date date) {
    DialogFragment dialog = null;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (requestCode) {
      case REQUEST_BIRTH_DATE:
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_BEST_VISIT:
        dialog = WorkProgressTimeDialogFragment.newInstance(date, R.string.chooseBestVisit);
        break;
      case SAVE_CHECK:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.submitConfirm);
        break;
      default:
        break;
    }
    dialog.setTargetFragment(CustomerRelationAddStaffFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_BIRTH_DATE && data != null) {
      Date birthDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      mBirthDate = MyDateUtil.dateToString(birthDate, MyDateUtil.TYPE_DATE);
      mTvBithDateAddDepartmentPerson.setText(mBirthDate);
      return;
    }
    if (requestCode == REQUEST_BEST_VISIT && data != null) {
      Date visitTime = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      mVisitTime = MyDateUtil.dateToString(visitTime, MyDateUtil.TYPE_ALL);
      mTvBestVisitTimeAddDepartmentPerson.setText(mVisitTime);
      return;
    }
    if (requestCode == SAVE_CHECK) {
      volleyPostSave(SAVE_CHECK);
    }
  }
}
